import { contextBridge, ipcRenderer } from 'electron'

export interface ServiceMethodInfo {
  className: string
  methodName: string
  ipcMethodName: string
  returnType?: string
  paramTypes?: string[]
}

export class AutoPreloadGenerator {
  /**
   * 自动从主进程获取信息并生成所有 preload
   */
  static async autoGenerate() {
    try {
      console.log('🚀 开始自动生成 preload...')
      
      // 重试机制：等待主进程服务就绪
      let serviceMethods: ServiceMethodInfo[] = []
      let retryCount = 0
      const maxRetries = 10
      
      while (serviceMethods.length === 0 && retryCount < maxRetries) {
        try {
          serviceMethods = await ipcRenderer.invoke('get-service-methods')
          if (serviceMethods.length === 0) {
            console.log(`⏳ 等待服务就绪... (尝试 ${retryCount + 1}/${maxRetries})`)
            await new Promise(resolve => setTimeout(resolve, 200))
            retryCount++
          }
        } catch (error) {
          console.log(`⏳ 主进程还未就绪，等待... (尝试 ${retryCount + 1}/${maxRetries})`)
          await new Promise(resolve => setTimeout(resolve, 200))
          retryCount++
        }
      }
      
      console.log(`📋 收到 ${serviceMethods.length} 个方法信息`, serviceMethods)
      
      if (serviceMethods.length === 0) {
        console.warn('⚠️ 没有收集到任何方法，请检查主进程服务是否正确注册')
        return
      }
      
      // 按服务分组
      const serviceGroups = this.groupByClassName(serviceMethods)
      
      // 为每个服务生成 preload
      Object.entries(serviceGroups).forEach(([className, methods]) => {
        this.generateServicePreload(className, methods)
      })
      
      console.log(`✅ 自动生成完成！共处理 ${Object.keys(serviceGroups).length} 个服务`)
      
    } catch (error) {
      console.error('❌ 自动生成 preload 失败:', error)
    }
  }

  private static groupByClassName(methods: ServiceMethodInfo[]): Record<string, ServiceMethodInfo[]> {
    return methods.reduce((groups, method) => {
      if (!groups[method.className]) {
        groups[method.className] = []
      }
      groups[method.className].push(method)
      return groups
    }, {} as Record<string, ServiceMethodInfo[]>)
  }

  private static generateServicePreload(className: string, methods: ServiceMethodInfo[]) {
    const exposedMethods: Record<string, (...args: any[]) => any> = {}
    
    methods.forEach(method => {
      exposedMethods[method.methodName] = (...args: any[]) => {
        console.log(`🔄 调用 ${className}.${method.methodName}，参数:`, args)
        return ipcRenderer.invoke(method.ipcMethodName, ...args)
      }
    })
    
    // 暴露到主世界（使用原始的服务名称）
    contextBridge.exposeInMainWorld(className, exposedMethods)
    
    console.log(`✅ 生成 ${className}，方法:`, methods.map(m => m.methodName))
    console.log(`🌍 已暴露到 window.${className}:`, exposedMethods)
  }
}